package com.mgs.tagger.model
{
	import com.mgs.tagger.appdata.dto.TagDTO;
	
	import mx.collections.ArrayCollection;
	import mx.collections.ICollectionView;
	import mx.controls.treeClasses.ITreeDataDescriptor;
	
	public class TagDescriptor implements ITreeDataDescriptor
	{
		public function TagDescriptor()
		{
		}
		
		public function getChildren(node:Object, model:Object=null):ICollectionView
		{
			return (node as TagUI).children;
		}
		
		public function hasChildren(node:Object, model:Object=null):Boolean
		{
			return (node as TagUI).children.length > 0;
		}
		
		public function isBranch(node:Object, model:Object=null):Boolean
		{
			// considéré come une branche si virtuel.
			return (node as TagUI).parent == null ||
				(node as TagUI).parent.parent == null;
		}
		
		public function getData(node:Object, model:Object=null):Object
		{
			return node;
		}
		
		public function addChildAt(parent:Object, newChild:Object, index:int, model:Object=null):Boolean
		{
			var parentModel:TagUI;
			if(parent != null){
				parentModel = (parent as TagUI);
				(parent as TagUI).children.addItemAt(newChild, index);
			}else{
				parentModel = ((model as ArrayCollection).getItemAt(0) as TagUI).parent;
				(model as ArrayCollection).addItemAt(newChild, index);
			}
			parentModel.tag.children.splice(index, 0, (newChild as TagUI).tag);
			(newChild as TagUI).parent = parentModel;
			return true;
		}
		
		public function removeChildAt(parent:Object, child:Object, index:int, model:Object=null):Boolean
		{
			if(parent != null){
				(parent as TagUI).children.removeItemAt(index);
			}else{
				(model as ArrayCollection).removeItemAt(index);
			}
			(child as TagUI).parent.tag.children.splice(index, 1);
			(child as TagUI).parent = null;
			return true;
		}
	}
}